import React, { useState, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import {
  Layout,
  Card,
  Button,
  Table,
  Input,
  Select,
  Space,
  Modal,
  message,
  Row,
  Col,
  Pagination,
  Descriptions
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import './Dashboard.css';

const { Option } = Select;

const staffData = Array.from({ length: 100 }).map((_, idx) => ({
  key: idx + 1,
  name: idx % 2 === 0 ? '张旭' : idx % 3 === 0 ? '李菲菲' : '张恒',
  phone: idx % 2 === 0 ? '18767256412' : '13208432854',
  type: idx % 3 === 0 ? '负责人' : '普通员工',
  tenant: idx % 2 === 0 ? '杭州久策科技有限公司' : '杭州耀云科技有限公司',
  building: idx % 2 === 0 ? 'C2幢' : 'A1幢',
  room: idx % 2 === 0 ? '206' : '308',
  regTime: '2022-01-23',
}));

const TenantStaffManage = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [searchForm, setSearchForm] = useState({
    tenantName: '',
    staffName: '',
    building: '',
    room: '',
    phone: '',
    type: '',
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const staffDataRef = useRef(staffData);
  const [filteredData, setFilteredData] = useState(staffDataRef.current);
  // 详情弹窗状态
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentDetail, setCurrentDetail] = useState(null);

  React.useEffect(() => {
    if (location.state && location.state.newStaff) {
      // 新数据插入到最前面
      staffDataRef.current = [location.state.newStaff, ...staffDataRef.current];
      setFilteredData([location.state.newStaff, ...filteredData]);
    }
    // eslint-disable-next-line
  }, [location.state]);

  const columns = [
    {
      title: '人员姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
    },
    {
      title: '联系方式',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '人员类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
    },
    {
      title: '租户名称',
      dataIndex: 'tenant',
      key: 'tenant',
      width: 200,
    },
    {
      title: '所属楼宇',
      dataIndex: 'building',
      key: 'building',
      width: 100,
    },
    {
      title: '房间名称',
      dataIndex: 'room',
      key: 'room',
      width: 100,
    },
    {
      title: '注册时间',
      dataIndex: 'regTime',
      key: 'regTime',
      width: 120,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space>
          <Button type="link" size="small" onClick={() => { setCurrentDetail(record); setDetailVisible(true); }}>详情</Button>
          <Button type="link" size="small" danger onClick={() => handleDelete(record)}>删除</Button>
        </Space>
      ),
    },
  ];

  const handleSearch = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      // 统计有多少个条件被填写
      const hasAnyCondition = Object.values(searchForm).some(val => val);
      if (!hasAnyCondition) {
        setFilteredData(staffDataRef.current);
        message.success('查询完成');
        setPage(1);
        return;
      }
      // 只要有一个条件匹配就显示
      const filtered = staffDataRef.current.filter(item => {
        return (
          (searchForm.tenantName && item.tenant.includes(searchForm.tenantName)) ||
          (searchForm.staffName && item.name.includes(searchForm.staffName)) ||
          (searchForm.building && item.building === searchForm.building) ||
          (searchForm.room && item.room.includes(searchForm.room)) ||
          (searchForm.phone && item.phone.includes(searchForm.phone)) ||
          (searchForm.type && item.type === searchForm.type)
        );
      });
      setFilteredData(filtered);
      message.success('查询完成');
      setPage(1);
    }, 800);
  };

  const handleReset = () => {
    setSearchForm({
      tenantName: '',
      staffName: '',
      building: '',
      room: '',
      phone: '',
      type: '',
    });
    setFilteredData(staffDataRef.current);
    setPage(1);
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的人员');
      return;
    }
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个人员吗？`,
      onOk() {
        // 删除 staffDataRef 和 filteredData 中对应项
        staffDataRef.current = staffDataRef.current.filter(item => !selectedRowKeys.includes(item.key));
        setFilteredData(prev => prev.filter(item => !selectedRowKeys.includes(item.key)));
        setSelectedRowKeys([]);
        message.success('删除成功');
      },
    });
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除人员“${record.name}”吗？`,
      onOk() {
        // 删除 staffDataRef 和 filteredData 中对应项
        staffDataRef.current = staffDataRef.current.filter(item => item.key !== record.key);
        setFilteredData(prev => prev.filter(item => item.key !== record.key));
        message.success('删除成功');
      },
    });
  };

  // 分页数据
  const pagedData = filteredData.slice((page - 1) * pageSize, page * pageSize);

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  return (
    <Layout className="dashboard-root">
      <div style={{ padding: '24px', background: '#f5f7fa', minHeight: '100vh' }}>
        <Card>
          {/* 顶部标题 */}
          <div style={{ marginBottom: 24, display: 'flex', alignItems: 'center' }}>
            <div style={{ width: 6, height: 28, background: '#3B5BDB', borderRadius: 3, marginRight: 12 }} />
            <h2 style={{ margin: 0, color: '#1f1f1f', fontWeight: 600, fontSize: 24 }}>租户人员管理</h2>
          </div>

          {/* 检索区 */}
          <Card style={{ marginBottom: 16, background: '#fafafa', border: '1px solid #e5e6eb' }} bodyStyle={{ padding: 20 }}>
            <Row gutter={24}>
              <Col span={6}>
                <Input
                  placeholder="请输入租户名称"
                  value={searchForm.tenantName}
                  onChange={e => setSearchForm({ ...searchForm, tenantName: e.target.value })}
                  style={{ marginBottom: 12 }}
                  allowClear
                />
              </Col>
              <Col span={6}>
                <Input
                  placeholder="请输入人员名称"
                  value={searchForm.staffName}
                  onChange={e => setSearchForm({ ...searchForm, staffName: e.target.value })}
                  style={{ marginBottom: 12 }}
                  allowClear
                />
              </Col>
              <Col span={6}>
                <Select
                  placeholder="请选择所属楼宇"
                  value={searchForm.building}
                  onChange={val => setSearchForm({ ...searchForm, building: val })}
                  style={{ width: '100%', marginBottom: 12 }}
                  allowClear
                >
                  <Option value="A1幢">A1幢</Option>
                  <Option value="C2幢">C2幢</Option>
                </Select>
              </Col>
              <Col span={6}>
                <Input
                  placeholder="请输入联系方式"
                  value={searchForm.phone}
                  onChange={e => setSearchForm({ ...searchForm, phone: e.target.value })}
                  style={{ marginBottom: 12 }}
                  allowClear
                />
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={6}>
                <Input
                  placeholder="请输入房间名称"
                  value={searchForm.room}
                  onChange={e => setSearchForm({ ...searchForm, room: e.target.value })}
                  style={{ marginBottom: 12 }}
                  allowClear
                />
              </Col>
              <Col span={6}>
                <Select
                  placeholder="请选择人员类型"
                  value={searchForm.type}
                  onChange={val => setSearchForm({ ...searchForm, type: val })}
                  style={{ width: '100%', marginBottom: 12 }}
                  allowClear
                >
                  <Option value="负责人">负责人</Option>
                  <Option value="普通员工">普通员工</Option>
                </Select>
              </Col>
              <Col span={12} style={{ textAlign: 'right' }}>
                <Button type="primary" style={{ marginRight: 12, background: '#009688', borderColor: '#009688' }} onClick={handleSearch}>查询</Button>
                <Button onClick={handleReset}>重置</Button>
              </Col>
            </Row>
          </Card>

          {/* 操作按钮 */}
          <div style={{ marginBottom: 16, textAlign: 'right' }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              style={{ marginRight: 16, background: '#1890ff', borderColor: '#1890ff' }}
              onClick={() => navigate('/tenant/staff/create')}
            >
              新增
            </Button>
            <Button danger icon={<DeleteOutlined />} onClick={handleBatchDelete}>批量删除</Button>
          </div>

          {/* 表格 */}
          <Table
            columns={columns}
            dataSource={pagedData}
            rowSelection={rowSelection}
            loading={loading}
            pagination={false}
            bordered
            scroll={{ x: 1200 }}
            style={{ background: '#fff' }}
          />

          {/* 详情弹窗 */}
          <Modal
            open={detailVisible}
            title="人员详情"
            footer={null}
            onCancel={() => setDetailVisible(false)}
            width={500}
          >
            {currentDetail && (
              <Descriptions column={1} bordered size="middle">
                <Descriptions.Item label="人员姓名">{currentDetail.name}</Descriptions.Item>
                <Descriptions.Item label="联系方式">{currentDetail.phone}</Descriptions.Item>
                <Descriptions.Item label="人员类型">{currentDetail.type}</Descriptions.Item>
                <Descriptions.Item label="租户名称">{currentDetail.tenant}</Descriptions.Item>
                <Descriptions.Item label="所属楼宇">{currentDetail.building}</Descriptions.Item>
                <Descriptions.Item label="房间名称">{currentDetail.room}</Descriptions.Item>
                <Descriptions.Item label="注册时间">{currentDetail.regTime}</Descriptions.Item>
              </Descriptions>
            )}
          </Modal>

          {/* 分页 */}
          <div style={{ marginTop: 16, textAlign: 'right' }}>
            <Pagination
              current={page}
              pageSize={pageSize}
              total={filteredData.length}
              showSizeChanger
              showQuickJumper
              pageSizeOptions={['10', '20', '50', '100']}
              showTotal={(total, range) => `共 ${total} 条`}
              onChange={(p, ps) => {
                setPage(p);
                setPageSize(ps);
              }}
              style={{ display: 'inline-block' }}
            />
          </div>
        </Card>
      </div>
    </Layout>
  );
};

export default TenantStaffManage; 